#!/bin/bash
#this script is started from $HOME/.jwmrc
#it builds JWM menu and syncronize with ROX/GTK bookmarks
#jwm -restart updates the JWM menu

export TEXTDOMAIN=jwm
export OUTPUT_CHARSET=UTF-8

export WORKDIR="$HOME/.jwm/tmp"
mkdir -p $WORKDIR

#sync with gtk and rox
echo -n > $WORKDIR/bookmark_list
echo -n > $WORKDIR/bookmark_list2
[ -s $HOME/.jwm/bookmarks ] && cat $HOME/.jwm/bookmarks >> $WORKDIR/bookmark_list2
[ -s $HOME/.config/rox.sourceforge.net/ROX-Filer/Bookmarks.xml ] && cut -d'>' -f2 $HOME/.config/rox.sourceforge.net/ROX-Filer/Bookmarks.xml | cut -d'<' -f1 >> $WORKDIR/bookmark_list2
[ -s $HOME/.gtk-bookmarks ] && cut -d'/' -f3- $HOME/.gtk-bookmarks >> $WORKDIR/bookmark_list2
grep -v "^$" $WORKDIR/bookmark_list2 | sed 's|%20| |g' | sort -u > $WORKDIR/bookmark_list3

#find description
while read J; do
	if [ "`grep -F '://' <<< "$J" 2> /dev/null`" ]; then
		#url
		XML=${XML}'\n<Program icon="internet.svg" label="'$J'" >exec defaultbrowser "'$J'"</Program>'
		echo "gtk-www|$J" >> $WORKDIR/bookmark_list
	elif [ -d "$J" ]; then
		#directory
		XML=${XML}'\n<Program icon="directory.svg" label="'$J'">exec rox -d "'$J'"</Program>'
		#sync gtk and rox
		#[ ! "`grep -F "$J" $HOME/.config/rox.sourceforge.net/ROX-Filer/Bookmarks.xml`" ] && sed -i "s|</bookmarks>|  <bookmark title=\"$J\">$J</bookmark>\n</bookmarks>|g" $HOME/.config/rox.sourceforge.net/ROX-Filer/Bookmarks.xml
		#TMP="$(echo "$J" | sed 's| |%20|g')"
		#[ ! "`grep -F "$TMP" $HOME/.gtk-bookmarks`" ] && echo "file://$TMP" >> $HOME/.gtk-bookmarks
		echo "gtk-directory|$J" >> $WORKDIR/bookmark_list
	else
		#file
		TMP="`find /usr/share/applications/ -iname "*$J*" -printf "%p\n" -exec grep -ilE -m1 "Exec=" {} \; | head -n 1`"
		if [ "$TMP" ]; then
			DESCRIPTION="`grep -im1 'Name=' $TMP | cut -d'=' -f2`"
			EXEC="`grep -im1 'Exec=' $TMP | cut -d'=' -f2`"
			ICON="`grep -im1 'Icon=' $TMP | cut -d'=' -f2`"
			echo "gtk-execute|$J" >> $WORKDIR/bookmark_list
			#write item to jwm bookmark menu
			XML=${XML}'\n<Program label="'$DESCRIPTION'" icon="'$ICON'">exec "'$EXEC'"</Program>'
		else
			DESCRIPTION="$J"
			echo "gtk-file|$J" >> $WORKDIR/bookmark_list
			#write item to jwm bookmark menu
			XML=${XML}'\n<Program label="'$DESCRIPTION'" icon="file.svg">exec rox "'$J'"</Program>'
		fi
	fi
done < $WORKDIR/bookmark_list3
#output to stdout - jwm menu
TMP="`echo -e "$XML" | sort`"
echo -e '<?xml version="1.0"?>
<JWM>
'"$TMP"'
<Separator/>
<Program icon="bookmark.svg" label="'$(gettext 'Edit Bookmarks')'">exec /usr/local/jwm_config/menu -bookmarks</Program>
</JWM>'

